package com.store.app.activity;

import android.app.AlertDialog;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.store.app.BaseActivity;
import com.store.app.ExitApplication;
import com.store.app.R;
import com.store.app.adapter.BalanceListAdapter;
import com.store.app.bean.CouponGoCashBean;
import com.store.app.bean.MoneyLogBean;
import com.store.app.http.Stores;
import com.store.app.imlife.utils.ToastTools;
import com.store.app.net.NetRequest;
import com.store.app.net.ifc.IOnHttpListener;
import com.store.app.utils.MoneyUtil;
import com.store.app.utils.SettingData;
import com.store.app.widget.AutoListView;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import de.greenrobot.event.EventBus;

/**
 * 零钱页面
 * Created by Administrator on 2017/2/28.
 */
public class MoneyBalanceActivity extends BaseActivity implements IOnHttpListener, View.OnClickListener {

    private String cash_froze = "";
    private String credit_balance = "";
    private LinearLayout retreat;
    private TextView tv_wallet;                 //余额
    private TextView tv_wallet_lock;            //冻结
    private TextView tv_xinyong;                //授信
    private AutoListView lv;
    private LinearLayout submit;                //提现
    private LinearLayout recharge;              //充值
    private NetRequest netRequest;
    private String usable_cash_balance = "0";//可用余额
    private LinearLayout ll_helper;
    private AlertDialog dialog;
    private int pageNum;
    private List<MoneyLogBean> logBeanList;
    private BalanceListAdapter adapter;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.balancerecord);
        cash_froze = getIntent().getStringExtra("cash_froze");
        credit_balance = getIntent().getStringExtra("credit_balance");
        pageNum = 1;
        init();
        initView();
        initData();
        ExitApplication.getInstance().addActivity(this);
    }
    private void init(){
        netRequest = new NetRequest(this);
        EventBus.getDefault().register(this);
    }
    private void initView() {
        retreat = (LinearLayout) findViewById(R.id.retreat);
        tv_wallet = (TextView) findViewById(R.id.tv_wallet);
        tv_wallet_lock = (TextView) findViewById(R.id.tv_wallet_lock);
        tv_xinyong = (TextView) findViewById(R.id.tv_xinyong);
        lv = (AutoListView) findViewById(R.id.lv);
        submit = (LinearLayout) findViewById(R.id.submit);
        recharge = (LinearLayout) findViewById(R.id.recharge);
        retreat.setOnClickListener(this);
        submit.setOnClickListener(this);
        recharge.setOnClickListener(this);
        ll_helper = (LinearLayout) findViewById(R.id.ll_helper);
        ll_helper.setOnClickListener(this);

        lv.setDivider(null);
        logBeanList = new ArrayList<>();
        adapter = new BalanceListAdapter(this,logBeanList);
        lv.setAdapter(adapter);

        lv.setOnRefreshListener(new AutoListView.OnRefreshListener() {

            @Override
            public void onRefresh() {
                pageNum = 1;
                netRequest.requestQueryCashLog(7, pageNum + "");
            }
        });

        lv.setOnLoadListener(new AutoListView.OnLoadListener() {

            @Override
            public void onLoad() {
                netRequest.requestQueryCashLog(6, pageNum + "");
            }
        });
        lv.onLoad();
    }
    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    private void initData() {

        //查询可用余额
        netRequest.requestUsableCashBalanceFind(1);
        if (!TextUtils.isEmpty(cash_froze)) {
            tv_wallet_lock.setText(cash_froze);
        }
        if (!TextUtils.isEmpty(credit_balance)) {
            tv_xinyong.setText(credit_balance);
        }
        tv_wallet.setText(MoneyUtil.addComma(Stores.cash_balance + ""));

    }

    @Override
    public void onAfinalFail() {
        if(lv!=null){
            lv.onLoadComplete();
            lv.onRefreshComplete();
        }
        ToastTools.show(this, "请检查本地网络！", Toast.LENGTH_SHORT);
    }

    @Override
    public void onExecuteSuccess(int requestId, String result, String msg) {
        //可用资产
        if (requestId == 1) {
            try {
                JSONObject jsonObject = new JSONObject(result);
                usable_cash_balance = jsonObject.optString("usable_cash_balance");
                Log.v("zyl", "设置可用金额：" + usable_cash_balance);
            } catch (Exception e) {
            }
        }
        //查询银行卡号
        else if (requestId == 2) {
            try {
                JSONObject obj_data = new JSONObject(result);
                if (!obj_data.toString().equals("{}")) {
                    String bankname = obj_data.optString("publishing_institutions");
                    String bankno = obj_data.optString("capital_account");
                    Intent intent = new Intent(this, WithDrawalsActivity.class);
                    intent.putExtra("bankname", bankname);
                    intent.putExtra("bankno", bankno);
                    intent.putExtra("usable_cash_balance", usable_cash_balance);
                    startActivity(intent);
                } else {
                    AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(this);
                    dialogBuilder.create();
                    LayoutInflater inflater = LayoutInflater.from(this);
                    View view = inflater.inflate(R.layout.balancedialog, null);
                    TextView tv_check = (TextView) view.findViewById(R.id.balandia_check);
                    tv_check.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            dialog.dismiss();
                            Intent intent = new Intent(MoneyBalanceActivity.this, BindBalanceActivity.class);
                            startActivity(intent);
                        }
                    });
                    dialogBuilder.setView(view);
                    dialog = dialogBuilder.show();
                }
            } catch (Exception e) {
            }
        }
        else if(requestId ==5){
            try {
                JSONObject jsonObject = new JSONObject(result);
                int vo = Integer.parseInt(jsonObject.optString("voucher_balance"));
                double banlance = Double.parseDouble(jsonObject.optString("cash_balance"));
                Stores.cash_balance = banlance;
                Stores.voucher_balance = vo;
                Stores.gold = jsonObject.getString("gold");
                tv_wallet.setText(MoneyUtil.addComma(Stores.cash_balance+""));
            } catch (Exception e) {
            }
        }
        //分页查询流水
        else if(requestId ==6){
            try {
                JSONObject data = new JSONObject(result);
                JSONArray listArr = data.getJSONArray("list");
                Gson gson = new Gson();
                List<MoneyLogBean> tempmoneyLogBeanList = new ArrayList<>();
                for (int i = 0; i < listArr.length(); i++) {
                    MoneyLogBean moneyLogBean = gson.fromJson(listArr.getJSONObject(i).toString(), MoneyLogBean.class);
                    tempmoneyLogBeanList.add(moneyLogBean);
                }
                lv.onLoadComplete();
                if (data.getJSONObject("page").getInt("page_no") == pageNum) {
                    lv.setResultSize(tempmoneyLogBeanList.size());
                    logBeanList.addAll(tempmoneyLogBeanList);
                    adapter.notifyDataSetChanged();
                    pageNum += 1;
                }
            } catch (JSONException e) {
            }
        }else if(requestId == 7){
            try {
                JSONObject data = new JSONObject(result);
                JSONArray listArr = data.getJSONArray("list");
                Gson gson = new Gson();
                List<MoneyLogBean> tempmoneyLogBeanList = new ArrayList<>();
                for (int i = 0; i < listArr.length(); i++) {
                    MoneyLogBean moneyLogBean = gson.fromJson(listArr.getJSONObject(i).toString(), MoneyLogBean.class);
                    tempmoneyLogBeanList.add(moneyLogBean);
                }
                lv.onRefreshComplete();
                if (data.getJSONObject("page").getInt("page_no") == pageNum) {
                    lv.setResultSize(tempmoneyLogBeanList.size());
                    logBeanList.clear();
                    logBeanList.addAll(tempmoneyLogBeanList);
                    adapter.notifyDataSetChanged();
                    pageNum += 1;
                }
            } catch (JSONException e) {
            }
        }
    }

    @Override
    public void onExecuteFail(int requestId, String msg) {
        ToastTools.showShort(this, msg);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.retreat:
                finish();
                break;
            //提现
            case R.id.submit:
                netRequest.requestQueryBankNo(2);
                break;
            //充值
            case R.id.recharge:
                startActivity(new Intent(this, BalanceRechargeActivity.class));
                break;
            //帮助
            case R.id.ll_helper:
                Intent intent = new Intent();
                intent.setClass(this, WebViewTGActivity.class);
                intent.putExtra("url", SettingData.WITH_DRAWALS_RULE);
                intent.putExtra("title", "提现规则");
                startActivity(intent);
                break;
        }
    }

    public void onEvent(CouponGoCashBean couponGoCashBean) {
        Log.v("zyl","onEvent 更新流水");
        if (couponGoCashBean.type == 2) {
            tv_wallet.setText(MoneyUtil.addComma(Stores.cash_balance + ""));
            pageNum = 1;
            netRequest.requestQueryCashLog(7, pageNum + "");
            netRequest.requestQueryAccount(5);
            netRequest.requestUsableCashBalanceFind(1);
        }
    }
}
